package com.example.speeddating.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.speeddating.config.TokenBlacklistService;
import com.example.speeddating.entity.TokenEntity;
import com.example.speeddating.annotaion.TokenCheck;
import com.example.speeddating.enums.ResponseCodeEnum;
import com.example.speeddating.tool.StringTools;
import com.example.speeddating.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenBlacklistService tokenBlacklistService;
    public static final String USER_KEY = "SMOYU";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        预检直接通过

        TokenCheck annotation;
        System.out.println("------拦截器------");
        response.setContentType("application/json;charset=UTF-8");
        if (request.getMethod().equals("OPTIONS")) {
            System.out.println("预检");
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        System.out.println("----getToken-----");
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(TokenCheck.class);
        } else {
            return true;
        }
        //默认不校验角色
        if (annotation == null || annotation.required() == false) {
            return true;
        }
        String token = request.getHeader("Authorization");
        log.info("token为：" + token);
        Method method = ((HandlerMethod) handler).getMethod();
        String methodName = method.getName();
        log.info("当前方法的名字为：{}",methodName);
        if (StringTools.isEmpty(token)) {
            log.info("token为空");
            if(methodName.equals("recommendList")||methodName.equals("articleDetail"))return true; //给个通道
            response.getWriter().append(handleResponse(null,"权限不足"));
            return false;
        }
        boolean blacklisted = tokenBlacklistService.isBlacklisted(token);
        if (blacklisted){
            response.getWriter().append(handleResponse(null,"权限不足"));
        }
//        解析token
        Claims claims = null;

        try {
            claims =  JwtTokenUtil.parseToken(token);
            log.info("解析claims1:{}", claims);
        } catch (Exception e) {
            response.getWriter().append(handleResponse(ResponseCodeEnum.CODE_602.getCode(),"token 校验失败！请重新登录"));
            return false;
        }
        if (claims == null) {
            response.getWriter().append(handleResponse(ResponseCodeEnum.CODE_602.getCode(),"token 校验失败！请重新登录"));
            return false;
        }
        log.info("token解析数据:{}", claims);
        //得到角色信息，只要有一个角色符合，就能返回
        String[] roles = annotation.roles().split(",");
        log.info("角色参数：" + roles);
        TokenEntity entity = new TokenEntity();
        log.info("id nickname",claims.get("id"),claims.get("nickname"));
        return true;
    }

    public static String handleResponse(Object code,String message) {
        JSONObject json=new JSONObject();
        json.put("message",message);
        if (code==null){
            json.put("code",500);
        }else {
            json.put("code",code);
        }
        json.put("data",null);
      return json.toString();
    }
}
